<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\MoneyTransaction;
use App\Models\MoneyBook;
use App\Models\MoneyCategory;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Storage;

class DetailController extends Controller
{
    /**
     * 显示明细页面
     */
    public function index(Request $request)
    {
        $user = Auth::user();

        // 获取用户的当前默认账本
        $moneyBook = $user->getCurrentDefaultBook();

        if (!$moneyBook) {
            return redirect()->route('user.books')->with('error', '请先创建一个账本');
        }

        return view('details.index', compact('moneyBook'));
    }

    /**
     * 获取明细数据
     */
    public function getData(Request $request)
    {
        $user = Auth::user();
        $moneyBook = $user->getCurrentDefaultBook();

        if (!$moneyBook) {
            return response()->json(['error' => '请先创建一个账本'], 400);
        }

        // 获取筛选参数
        $year = $request->get('year', date('Y'));
        $month = $request->get('month', date('n'));
        $type = $request->get('type', 'all'); // all, income, expense
        $dateFrom = $request->get('date_from');
        $dateTo = $request->get('date_to');
        $search = $request->get('search');
        $userId = $request->get('user_id');
        $categoryId = $request->get('category_id');
        $subCategoryId = $request->get('subcategory_id');

        // 构建查询
        $query = MoneyTransaction::where('book_id', $moneyBook->id)
            ->with(['category', 'subCategory', 'user']);

        // 时间筛选
        if ($dateFrom && $dateTo) {
            $query->whereBetween('transaction_date', [$dateFrom, $dateTo]);
        } else {
            // 默认按年月筛选
            $startDate = Carbon::create($year, $month, 1)->startOfMonth();
            $endDate = Carbon::create($year, $month, 1)->endOfMonth();
            $query->whereBetween('transaction_date', [$startDate, $endDate]);
        }

        // 类型筛选
        if ($type !== 'all') {
            $typeValue = $type === 'income' ? MoneyCategory::TYPE_INCOME : MoneyCategory::TYPE_EXPENSE;
            $query->whereHas('category', function($q) use ($typeValue) {
                $q->where('type', $typeValue);
            });
        }

        // 用户筛选
        if ($userId && $userId !== 'all') {
            $query->where('user_id', $userId);
        }

        // 分类筛选
        if ($categoryId) {
            $query->where('category_id', $categoryId);
        }

        // 子分类筛选
        if ($subCategoryId) {
            $query->where('sub_category_id', $subCategoryId);
        }

        // 搜索筛选
        if ($search) {
            $query->where('description', 'like', '%' . $search . '%');
        }

        // 获取数据并按日期分组
        $transactions = $query->orderBy('transaction_date', 'desc')
            ->orderBy('created_at', 'desc')
            ->get();

        // 按日期分组
        $groupedTransactions = $transactions->groupBy(function($transaction) {
            return $transaction->transaction_date->format('Y-m-d');
        });

        // 格式化数据
        $result = [];
        foreach ($groupedTransactions as $date => $dayTransactions) {
            $carbonDate = Carbon::parse($date);
            $dayIncome = $dayTransactions->where('category.type', MoneyCategory::TYPE_INCOME)->sum('amount');
            $dayExpense = $dayTransactions->where('category.type', MoneyCategory::TYPE_EXPENSE)->sum('amount');

            $result[] = [
                'date' => $date,
                'formatted_date' => $this->formatDate($carbonDate),
                'weekday' => $this->getWeekday($carbonDate),
                'income' => $dayIncome,
                'expense' => $dayExpense,
                'transactions' => $dayTransactions->map(function($transaction) {
                    return [
                        'id' => $transaction->id,
                        'amount' => $transaction->amount,
                        'note' => $transaction->description,
                        'type' => $transaction->category->type === MoneyCategory::TYPE_INCOME ? 'income' : 'expense',
                        'category_name' => $transaction->category->name,
                        'subcategory_name' => $transaction->subCategory ? $transaction->subCategory->name : '',
                        'category_icon' => $transaction->subCategory ? $transaction->subCategory->icon : $transaction->category->icon,
                        'user_name' => $transaction->user->nickname,
                        'user_avatar_url' => $transaction->user->avatar_url,
                        'created_at' => $transaction->created_at->format('H:i')
                    ];
                })->values()
            ];
        }

        return response()->json($result);
    }

    /**
     * 获取筛选选项数据
     */
    public function getFilterOptions(Request $request)
    {
        $user = Auth::user();
        $moneyBook = $user->getCurrentDefaultBook();

        if (!$moneyBook) {
            return response()->json(['error' => '请先创建一个账本'], 400);
        }

        // 获取账本成员
        $users = $moneyBook->users()->select('users.id', 'users.nickname', 'users.avatar')->get();

        // 获取分类
        $categories = MoneyCategory::where('book_id', $moneyBook->id)
            ->with('subCategories')
            ->orderBy('type')
            ->orderBy('sort')
            ->get();

        return response()->json([
            'users' => $users,
            'categories' => $categories->map(function($category) {
                return [
                    'id' => $category->id,
                    'name' => $category->name,
                    'icon' => $category->icon,
                    'type' => $category->type,
                    'subcategories' => $category->subCategories->map(function($sub) {
                        return [
                            'id' => $sub->id,
                            'name' => $sub->name,
                            'icon' => $sub->icon
                        ];
                    })
                ];
            })
        ]);
    }

    /**
     * 格式化日期显示
     */
    private function formatDate(Carbon $date)
    {
        $today = Carbon::today();
        $yesterday = Carbon::yesterday();

        if ($date->isSameDay($today)) {
            return '今天';
        } elseif ($date->isSameDay($yesterday)) {
            return '昨天';
        } else {
            return $date->format('n月j日');
        }
    }

    /**
     * 获取星期几
     */
    private function getWeekday(Carbon $date)
    {
        $weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        return $weekdays[$date->dayOfWeek];
    }
}
